package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashSet;

/**
 * 用户操作
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;
    //获得当前登录用户的用户名
    @RequestMapping("/getUsername")
    public Result getUser(){
        //当Spring security完成认证后，会将当前用户信息保存到框架提供的上下文对象
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(user);
        if(user != null){
            String username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        }

        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }



    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return userService.pageQuery(queryPageBean);
    }

    //findSelected
    @RequestMapping("/findSelected")
    public Result findSelected(Integer userId){
        try{
            Integer[]roleIds=userService.findSelected(userId);
            return new Result(true,"回显数据成功",roleIds);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"回显数据失败");
        }

    }

    @RequestMapping("/editRoles")
    public Result editRoles(Integer userId,@RequestBody Integer[]roleIds){
        try{
            userService.editRoles(userId,roleIds);
            return new Result(true,"回显数据成功",roleIds);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"回显数据失败");
        }

    }

    @RequestMapping("/showMenusByUsername")
    public Result showMenusByUsername(String username){
        try{
            LinkedHashSet<Menu>menuList=userService.showMenusByUsername(username);
            return new Result(true,"回显数据成功",menuList);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"回显数据失败");
        }

    }
}
